package com.dingding.configuration;

import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * 全局时间格式化 去掉 "T"
 *
 * @author kangjia
 * @date 2019/10/31 10:32
 */
@Configuration
public class LocalDateTimeConfig {

  @Value("${spring.jackson.date-format}")
  private String dateTimeFormat;

  private static final String dateFormat = "yyyy-MM-dd";

  /**
   * 全局时间参数出参转换配置
   * @return
   */
  @Bean
  public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
    return builder -> {
      builder.simpleDateFormat(dateTimeFormat);
      builder.serializers(new LocalDateSerializer(DateTimeFormatter.ofPattern(dateFormat)));
      builder.serializers(new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(dateTimeFormat)));
    };
  }

  /** 全局时间参数入参转换类 description:LocalDateTime转换器，用于转换RequestParam和PathVariable参数 接收毫秒级时间戳字符串——>LocalDateTime */
  @Bean
  public Converter<String, LocalDate> localDateConverter() {
    return new Converter<String, LocalDate>() {
      @Override
      public LocalDate convert(String source) {
        return LocalDate.parse(source, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
      }
    };
  }

  /** 全局时间参数入参转换类 description:LocalDateTime转换器，用于转换RequestParam和PathVariable参数 接收毫秒级时间戳字符串——>LocalDateTime */
  @Bean
  public Converter<String, LocalDateTime> localDateTimeConverter() {
    return new Converter<String, LocalDateTime>() {
      @Override
      public LocalDateTime convert(String source) {
        return LocalDateTime.parse(source, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
      }
    };
  }

  /** 全局时间参数入参转换类 description:java.util.Date转换器 接收毫秒级时间戳字符串——>Date */
  @Bean
  public Converter<String, Date> dateConverter() {
    return new Converter<String, Date>() {
      @Override
      public Date convert(String source) {
        try {
          return new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse(source);
        } catch (ParseException e) {
          return null;
        }
      }
    };
  }


}
